package com.exahq.controller;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.system.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.exahq.common.lang.Result;
import com.exahq.entity.User;
import com.exahq.entity.Userinfo;
import com.exahq.entity.Viwe;
import com.exahq.service.UserService;
import com.exahq.service.UserinfoService;

import com.exahq.service.ViweService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lhq
 * @since 2021-01-25
 */
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
    UserService userService;
@Autowired
    UserinfoService userinfoService;
    @Autowired
    ViweService viweService;

    /**
     * 登录
     * @param u
     * @return
     */
    @RequestMapping(value = "login",method =RequestMethod.POST)
    @PostMapping("login")
    public Result login(@RequestBody User u){
        Map<Object,Object> map =new HashMap<Object, Object>();
        Userinfo userinfo =new Userinfo();
        Integer id=0;
        Boolean flag =false;
        //JSONObject json_test = JSONObject.fromObject(mapData);
        QueryWrapper<User> userQueryWrapper =new QueryWrapper<User>();
        //userQueryWrapper.eq("openId",u.getOpenId());
        userQueryWrapper.eq("phone",u.getPhone());
        userQueryWrapper.eq("del_flag",1);
        User user = userService.getOne(userQueryWrapper);
        if (user == null){
            user =new User();
            user.setOpenId(u.getOpenId());
            user.setPassword(SecureUtil.md5(u.getPassword()));
            user.setPhone(u.getPhone());
            user.setUStatus(1);
            userService.add(user);
            User ud =userService.getOne(userQueryWrapper);
            map.put("id",ud.getUid());
            Viwe viwe =viweService.getById(1);
            viwe.setUserCount(viwe.getUserCount()+1);
            viweService.saveOrUpdate(viwe);
        }else {
           QueryWrapper<Userinfo> userinfoQueryWrapper =new QueryWrapper<Userinfo>();
            userinfoQueryWrapper.eq("del_flag",1);
            userinfoQueryWrapper.eq("uid",user.getUid());
            userinfo =userinfoService.getOne(userinfoQueryWrapper);
            flag=true;
        }

        map.put("flag",flag);
        map.put("userInfo",userinfo);
        return Result.succ(map);
    }

}
